﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel;

namespace XbdSoft.Client
{
    public static  class ServiceFactory
    {
        public static T Create<T>(string address)
        {
            var binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = 2000000000;
            var endPointAddress = new EndpointAddress(address);
            ChannelFactory<T> myChannelFactory = new ChannelFactory<T>(binding,endPointAddress);
            return myChannelFactory.CreateChannel();
        }
    }

    public class ServiceObject<T>:IDisposable
    {
        #region Ctor
        private readonly ChannelFactory<T> channelFactory = null;

        public ServiceObject(string address)
        {
            var binding = new BasicHttpBinding(); 
            binding.MaxReceivedMessageSize = 2000000000;
            binding.ReceiveTimeout = TimeSpan.FromSeconds(60); ;
            var endPointAddress = new EndpointAddress(address);
            channelFactory = new ChannelFactory<T>(binding, endPointAddress);
            Object = channelFactory.CreateChannel();           
        }
        #endregion
        

        #region Service
        public T Object { get; set; }
        #endregion


        #region IDisposable Members

        public void Dispose()
        {
            channelFactory.Close();
        }
        #endregion

        #region 
        public bool CanOpen()
        {
            bool canOpen = true;
            try
            {
                if(channelFactory.State != CommunicationState.Opened)
                    channelFactory.Open();
                canOpen = channelFactory.State == CommunicationState.Opened;
                
            }
            catch 
            {
                canOpen = false;
            }
            return canOpen;
        }
        #endregion
    }
}
